﻿<%@ WebHandler Language="C#" Class="RegionBlockMgr" %>

using System;
using System.Web;
using System.Text;
using System.Collections.Generic;
using Chenxin.Lib.Utility;

public class RegionBlockMgr : AjaxHandlerBase
{
    public override void RequestProcess(HttpContext context)
    {
        context.Response.AddHeader("pragma", "no-cache");
        context.Response.AddHeader("cache-control", "");
        context.Response.CacheControl = "no-cache";
        switch (context.Request["op"].ToLower())
        {
            case "gettree":
                GetTree(context);
                break;
            case "add":
                Add(context);
                break;
            case "del":
                Del(context);
                break;
        }
    }

    /// <summary>
    /// 获取Tree
    /// </summary>
    /// <param name="context"></param>
    private void GetTree(HttpContext context)
    {

        StringBuilder listSb = new StringBuilder();
        switch(context.Request["type"])
        {
            case "city":
                StringBuilder str = new StringBuilder();
                str.Append("DepartProperty=100");
                if (CurrentUserInfo.ContainsPermit(Constants.Permit_ViewAllNode))
                {
                    str.Append(" and (1=1) ");
                }
                //查看本城市节点权限
                else if (CurrentUserInfo.ContainsPermit(Constants.Permit_ViewCityNode))
                {
                    str.AppendFormat(" and cityid='{0}' ", CurrentUserInfo.CityId);
                }

                List<Chenxin.Lib.Hr.Entity.Hr_DepartmentInfo> dlist = Chenxin.Lib.Hr.DAL.Hr_DepartmentInfo.GetListArray(str.ToString(), "City");
                foreach (Chenxin.Lib.Hr.Entity.Hr_DepartmentInfo d in dlist)
                {
                    listSb.AppendFormat("{{val:'{0}',txt:'{1}',type:'city',remark:'城市'}},", d.DepartId, d.DepartName);
                }
                break;
            case "region":
                
                List<Chenxin.Lib.House.Entity.DataDictionary> list = Chenxin.Lib.House.DAL.DataDictionary.GetListArray("ItemKey='System.Region' and CityId='"+context.Request["fatherid"]+"'", "ItemIndex desc");
                foreach (Chenxin.Lib.House.Entity.DataDictionary d in list)
                {
                    listSb.AppendFormat("{{val:'{0}',txt:'{1}',type:'region',itemindex:'{2}',cityid:'{3}',city:'{4}',itemtype:'{5}',itemkey:'{6}',remark:'区域'}},", d.RecordId, d.ItemValue, d.ItemIndex, d.CityId,d.City,d.ItemType,d.ItemKey);
                }
                break;
            default:
                string strWhere = "ItemKey='"+context.Request["itemkey"]+"' and CityId='" + context.Request["cityid"] + "'";
                strWhere += " and len(itemindex)>3";
                strWhere = strWhere + string.Format(" AND (substring(Convert(varchar(50), itemIndex), 1 ,len(itemIndex)-3)) ='{0}'", context.Request["itemindex"]);
                List<Chenxin.Lib.House.Entity.DataDictionary> xlist = Chenxin.Lib.House.DAL.DataDictionary.GetListArray(strWhere.ToString(), "ItemIndex desc");

                foreach (Chenxin.Lib.House.Entity.DataDictionary d in xlist)
                {
                    listSb.AppendFormat("{{val:'{0}',txt:'{1}',type:'block',leaf:true,itemindex:'{2}',itemtype:'{3}',itemkey:'{4}',remark:'板块'}},", d.RecordId, d.ItemValue, d.ItemIndex, d.ItemType, d.ItemKey);
                }
                break;
        }
        if (listSb.Length > 0)
        {
            listSb.Remove(listSb.Length - 1,1);
        }
        context.Response.Write(string.Format("{{success:1,msg:'',data:{{items:[{0}]}}}}", listSb.ToString()));        
        
    }

    public void Add(HttpContext context)
    {
        try
        {
            
            Chenxin.Lib.House.Entity.DataDictionary model = (Chenxin.Lib.House.Entity.DataDictionary)JsonHelp.Convert2Entity(context.Request["model"], typeof(Chenxin.Lib.House.Entity.DataDictionary));

            model.RecordId = Guid.NewGuid();
            if (model.ItemKey == "System.Block" || model.ItemKey == "System.Area")//添加板块
            {
                //model.ItemIndex = Chenxin.Lib.House.DAL.DataDictionary.GetBlockItemIndex(Convert.ToInt32(context.Request["region"]), model.CityId);
                model.ItemIndex = Chenxin.Lib.House.DAL.DataDictionary.GetBlockItemIndex(Convert.ToInt32(context.Request["region"]), model.CityId, model.ItemKey);

                string strWhere = "ItemKey='"+model.ItemKey+"' and CityId='" + model.CityId + "'";
                strWhere += string.Format(" and len(itemindex)>3 and ItemValue='{0}'",model.ItemValue);
                strWhere = strWhere + string.Format(" AND (substring(Convert(varchar(50), itemIndex), 1 ,len(itemIndex)-3)) ='{0}'", context.Request["region"]);

                if (Chenxin.Lib.House.DAL.DataDictionary.Exists(strWhere))
                {
                    context.Response.Write("{success:0,msg:'该板块已经存在，不能添加',data:''}");
                    return;
                }
            }
            else//添加区域
            {
                if(Chenxin.Lib.House.DAL.DataDictionary.Exists(string.Format("ItemValue='{0}' and CityId='{1}' and ItemKey='System.Region'",model.ItemValue,model.CityId)))
                {
                    context.Response.Write("{success:0,msg:'该区域已经存在，不能添加',data:''}");
                    return;         
                }
            }


            Chenxin.Lib.House.DAL.DataDictionary.Add(model);

            //删除
            Chenxin.Lib.Cache.CacheService cs = new Chenxin.Lib.Cache.CacheService(Chenxin.Lib.Cache.CacheConn.xCacheConn.DICTDATA);

            cs.Delete(string.Format(Chenxin.Lib.Cache.CacheDataType.DICTDATA, model.ItemKey + context.Request["region"] + "." + model.CompanyId.ToString()));
            cs.Delete(string.Format(Chenxin.Lib.Cache.CacheDataType.DICTDATA, model.ItemKey + context.Request["region"] + "." + model.CityId.ToString()));


            //添加用户操作日志 2010-5-11 王玮 Add
            AddLog("" + CurrentUserInfo.UserName + "添加了一个数据字典参数:标识值为[" + model.ItemKey + "]的[" + model.ItemValue + "]",
                    OperationType.OperationTypeComboList()["OprType_DataDictionaryAdd"].ToString());

            context.Response.Write("{success:1,msg:'添加成功！',data:'" + model.RecordId + "'}");       
        }
        catch (Exception e)
        {
            context.Response.Write("{success:0,msg:'" + e.Message + "',data:''}");
        }


    }

    /// <summary>
    /// 删除
    /// </summary>
    /// <param name="context"></param>
    private void Del(HttpContext context)
    {
        try
        {
            if (context.Request["modelid"] != null)
            {
                Chenxin.Lib.House.Entity.DataDictionary model = Chenxin.Lib.House.DAL.DataDictionary.GetModel(new Guid(context.Request["modelid"]));

                if (model != null)
                {
                    Chenxin.Lib.House.DAL.DataDictionary.Delete(new Guid(context.Request["modelid"]));

                    //删除
                    Chenxin.Lib.Cache.CacheService cs = new Chenxin.Lib.Cache.CacheService(Chenxin.Lib.Cache.CacheConn.xCacheConn.DICTDATA);
                    cs.Delete(string.Format(Chenxin.Lib.Cache.CacheDataType.DICTDATA, model.ItemKey + context.Request["region"] + "." + model.CityId.ToString()));
                    cs.Delete(string.Format(Chenxin.Lib.Cache.CacheDataType.DICTDATA, model.ItemKey + context.Request["region"] + "." + model.CompanyId.ToString()));

                    if (model.ItemKey == "System.Region") 
                    {
                        Chenxin.Lib.House.DAL.DataDictionary.DeleteBlock(Convert.ToInt32(model.ItemIndex), model.CityId);

                    }

                    //添加用户操作日志 2010-5-11 王玮 Add
                    AddLog("" + CurrentUserInfo.UserName + "删除了一个数据字典参数:标识值为[" + model.ItemKey + "]的[" + model.ItemValue + "]",
                            OperationType.OperationTypeComboList()["OprType_DataDictionaryDel"].ToString());

                    context.Response.Write("{success:'1',msg:'删除成功！',data:''}");
                }
                else
                {

                    context.Response.Write("{success:'0',msg:'删除失败！',data:''}");
                }
            }
            else
            {
                context.Response.Write("{success:'0',msg:'删除失败,请选择一条记录！',data:''}");
            }
        }
        catch(Exception e)
        {
            context.Response.Write("{success:'0',msg:'删除失败！"+e.Message+"',data:''}");
        }
    }

}